<?php

namespace common\logics;

use Yii;
use yii\helpers\ArrayHelper;

/**
 * This is the model class for table "{{%shop_attribute}}".
 *
 * @property int $id
 * @property string $name 规格名称
 * @property int $group_id 规格组ID
 * @property int $type_id 分类ID
 * @property int $screen 是否筛选项
 * @property int $status 状态
 * @property int $created_at 创建时间
 * @property int $updated_at 更新时间
 * @property int $deleted_at 删除时间
 */
class ShopSpecLogic extends \common\models\shop\ShopAttribute {

    /**
     * {@inheritdoc}
     */
    public static function tableName() {
        return '{{%shop_attribute}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules() {
        return [
            [['name'], 'required'],
            [['group_id', 'type_id', 'screen', 'status', 'created_at', 'updated_at', 'deleted_at'], 'integer'],
            [['name'], 'string', 'max' => 50],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels() {
        return [
            'id' => 'ID',
            'name' => '规格名称',
            'group_id' => '规格组ID',
            'type_id' => '分类ID',
            'screen' => '是否筛选项',
            'status' => '状态',
            'created_at' => '创建时间',
            'updated_at' => '更新时间',
            'deleted_at' => '删除时间',
        ];
    }

    public function getValue() {
        return $this->hasMany(ShopAttributeValue::className(), ['attribute_id' => 'id']);
    }

    public function getGroup() {
        return $this->hasOne(ShopAttributeGroup::className(), ['id' => 'group_id']);
    }

    public function getTags() {
        return $this->getValue()->select(['name'])->column();
    }

    public function getText() {
        $label = '';
        if ($this->group) {
            $label = ' ' . Html::tag('kbd', $this->group->name);
        }
        return $this->name . $label;
    }

    public static function activeList($useLabel = true) {
        $data = static::find()->all();
        if ($useLabel && !empty($data)) {
            $array = [];
            foreach ($data as $item) {
                $array[$item->id] = $item->text;
            }
            return $array;
        }
        return ArrayHelper::map($data, 'id', 'name');
    }

}
